package org.celstec.mobilegame.server;

import java.io.ByteArrayInputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import javax.jdo.PersistenceManager;

import org.celstec.mobilegame.LocatoryServlet;
//import org.celstec.mobilegame.MobileObjectCreator;
import org.celstec.mobilegame.client.LongLatPoint;
import org.celstec.mobilegame.client.SubmitGameService;
import org.celstec.mobilegame.gameLoaders.LocatoryLoader;
import org.celstec.mobilegame.locatory.Card;
import org.celstec.mobilegame.locatory.CardLocation;
import org.celstec.mobilegame.locatory.Locatory;
import org.celstec.mobilegame.locatory.LocatoryPlay;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;

import com.google.appengine.api.datastore.Key;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class SubmitGameServiceImpl extends RemoteServiceServlet implements
		SubmitGameService {


	
	public int submitGame(String gameContent, String Play) {
		try {
			// TODO Auto-generated method stub
			
			Document doc = loadDocumentAsString(gameContent);
			Locatory locatory = LocatoryLoader.load(doc.getRootElement());
			locatory.name = Play;
//			LocatoryPlay play = locatory.createPlay(Play);
			//LocatoryServlet.games.put(Play, locatory);
			makeGamePersistent(locatory);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 2;
	}
	
	public static void makeGamePersistent(Locatory loc){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
//			Iterator it = loc.hm.keySet().iterator();
//			while (it.hasNext()) {
//				pm.makePersistent(loc.hm.get(it.next()));
//			}
			pm.makePersistent(loc);
		} finally {			
			pm.close();

		}
	}
	
	public static void makeObjectPersistent(Object o){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			
			pm.makePersistent(o);
		} finally {			
			pm.close();

		}
	}

	public String[] getAvailableGames() {
		// TODO Auto-generated method stub
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			String query = "select from " + Locatory.class.getName();
			List<Locatory> games = (List<Locatory>) pm.newQuery(query).execute();
			String [] retString = new String[games.size()];
			Iterator<Locatory> it = games.iterator();
			int i =0;
			while (it.hasNext()) {
				retString[i++] =  it.next().name;
			}
			return retString;
		} finally {			
			pm.close();

		}
	}
	
	

	public int createPlay(String playName, String gameName) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			String query = "select from " + Locatory.class.getName()+" where name =='"+gameName+"'";
			List<Locatory> games = (List<Locatory>) pm.newQuery(query).execute();
			if (games.size()!=0){
				LocatoryPlay play = games.get(0).createPlay(playName);
				//LocatoryServlet.hm.put(playName, play);
				pm.makePersistent(play);
			}
		} finally {			
			pm.close();

		}
		return 1;
		
	}


	public LongLatPoint[] getLongLatPairs(String game) {
		// TODO Auto-generated method stub
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			String query = "select from " + Locatory.class.getName()+" where name =='"+game+"'";
			List<Locatory> games = (List<Locatory>) pm.newQuery(query).execute();
			if (games.size()!=0){
				Locatory locatory = games.get(0);
//				LocatoryServlet.hm.put(playName, play);
				Set<Key> locs = locatory.keysLocations;
				LongLatPoint[] returnValue = new LongLatPoint[locs.size()];
				Iterator it = locs.iterator();
				int i =0;
				while (it.hasNext()) {
					
					CardLocation loc = CardLocation.getObject((Key)it.next());
					returnValue[i++] = new LongLatPoint(loc.lat,loc.lon);
				}
				return returnValue;

			}
		} finally {			
			pm.close();

		}
		return null;
	}
	
	public static Document loadDocumentAsString(String s)throws Exception{
		SAXBuilder saxBuilder = new SAXBuilder();
		ByteArrayInputStream bytes = new ByteArrayInputStream(s.getBytes("UTF-8"));

		return saxBuilder.build(bytes);
	}
}
